import React, {Component} from 'react';
import {Card, message, Table, Button} from "antd";
import moment from "moment";
import {reqGetSpiderTasks, reqDeleteSpiderTask, reqGetSpiderTask, reqRunSpiderTask} from '../../../api/tasks'
import {MinusOutlined, PlusOutlined} from "@ant-design/icons";
import ModalForm from "./ModalForm";

// 爬虫管理
export default class SpiderTasks extends Component {

  state = {
    totalCount: 0,
    listQuery: {
      page: 1,
      page_size: 10,
      order: undefined
    },
    list: [],
    loading: false,
    selectedRowKeys: [], // 选择删除
    isModalVisible: false, // 对话框显隐
    btnLoading: false,
    _id: ''
  }

  initColumns() {
    this.columns = [
      {
        title: '任务名称',
        dataIndex: 'name',
        align: 'center'
      },
      {
        title: '文件路径',
        dataIndex: 'path',
        align: 'center',
        ellipsis: true
      },
      {
        title: '运行命令',
        dataIndex: 'command',
        align: 'center',
        width: 150,
        ellipsis: true
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        align: 'center',
        render: (create_time) => moment(create_time).format('YYYY-MM-DD HH:mm'),
        sorter: true,
        sortDirections: ['ascend', 'descend'],
        defaultSortOrder: 'descend'
      },
      {
        title: '更新时间',
        dataIndex: 'update_time',
        align: 'center',
        render: (update_time) => moment(update_time).format('YYYY-MM-DD HH:mm'),
        sorter: true,
        sortDirections: ['ascend', 'descend'],
      },
      {
        title: '操作',
        align: 'center',
        width: 300,
        render: (text, record, index) => <>
          <Button style={{ marginRight: '10px' }} type="primary" onClick={() => this.handleEdit(record)}>编辑</Button>
          <Button style={{ marginRight: '10px' }}
                  onClick={() => this.handleRun(record)}
                  loading={this.state.btnLoading && record._id === this.state._id}>运行</Button>
          {/*<Button type="primary" danger>暂停</Button>*/}
        </>
      }
    ]
  }

  UNSAFE_componentWillMount() {
    this.initColumns();
  }

  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys});
  }

  // 获取所有任务
  async getSpiderTasks() {
    try {
      this.setState({loading: true});
      const {data: res} = await reqGetSpiderTasks(this.state.listQuery);
      this.setState({
        totalCount: res.total_count,
        list: res.items,
        loading: false
      })
    } catch (e) {
      this.setState({loading: false});
      message.error(e.data.name || e.data.message)
    }
  }

  componentDidMount() {
    this.getSpiderTasks();
  }

  onChange = (pagination, filters, sorter, extra) => {
    const {current, pageSize} = pagination;
    let order = sorter.order; // 排序的模式 asc升序 desc降序
    order = order !== undefined ? order.replace('end', '') : 'desc';
    const field = sorter.field; // 排序的字段
    const listQuery = Object.assign({},{page: current, page_size: pageSize, order, sort: field})
    this.setState({
      listQuery
    }, () => {
      this.getSpiderTasks();
    });
  }

  // 运行
  handleRun = async (record) => {
    try {
      this.setState({
        _id: record._id,
        btnLoading: true
      })
      message.success('开始运行！');
      const {data: res} = await reqRunSpiderTask(record);
      if (res.code === 0) {
        message.success('运行成功！');
      } else {
        message.success('运行失败！');
      }
    } catch (e) {
      message.error(e.data.message);
    }
    this.setState({
      _id: '',
      btnLoading: false
    })
  }

  // 编辑
  handleEdit = async (record) => {
    try {
      const {data: res} = await reqGetSpiderTask(record._id);
      if (res) {
        this.formData = res;
        this.setState({
          isModalVisible: true
        })
      }
    } catch (e) {
      message.error(e.message);
    }
  }

  // 添加
  handleAddClick = () => {
    this.setState({isModalVisible: true});
  }

  // 关闭对话框
  handleCloseDialog = (val, state)  => {
    this.setState({isModalVisible: val});
    this.formData = {};
    if (state === 'add' || state === 'update') { // 创建成功
      this.getSpiderTasks();
    }
  }

  // 删除
  handleDeleteClick = () => {
    if (this.state.selectedRowKeys.length < 1) {
      message.warning('请至少选中1条待删除的数据！');
    } else {
      reqDeleteSpiderTask({ids: this.state.selectedRowKeys}).then(res => {
        if (res.status === 204) {
          message.success('删除成功！');
          this.getSpiderTasks();
        } else {
          message.error('删除失败！');
        }
      })
    }
  }

  CardExtraContent = (
    <>
      <Button type='primary'
              onClick={this.handleAddClick}
              style={{ marginRight: '10px' }}
              icon={ <PlusOutlined /> }
      >
        添加
      </Button>
      <Button type="primary" onClick={this.handleDeleteClick} icon={ <MinusOutlined /> } danger>
        删除
      </Button>
    </>
  )

  render() {
    const {selectedRowKeys, list, loading, totalCount, isModalVisible} = this.state;

    const pagination = {
      position: ['bottomCenter'],
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: [10, 20],
      total: totalCount
    }

    // 启用带选择的框
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    return (
      <>
        <Card title='爬虫任务' extra={this.CardExtraContent}>
          <Table rowSelection={rowSelection}
                 scroll={{x: 800}}
                 loading={loading}
                 columns={this.columns}
                 rowKey='_id'
                 onChange={this.onChange}
                 pagination={pagination}
                 dataSource={list}
          />
        </Card>
        <ModalForm isModalVisible={isModalVisible}
                   formData={this.formData}
                   closeDialog={this.handleCloseDialog}/>
      </>
    )
  }
}
